<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品代码" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入产品代码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品分类" prop="productCategory">
        <el-select v-model="queryParams.productCategory" @change="handleQuery" placeholder="请输入产品类型" clearable size="small">
          <el-option
            v-for="(item, index) in configCategoryOptions"
            :key="index"
            :label="item.categoryName"
            :value="item.categoryCode"
          />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="产品来源" prop="productSourceType">
        <el-select v-model="queryParams.productSourceType" placeholder="请选择产品来源" clearable size="small">
          <el-option
            v-for="(item, index) in productSourceTypeOptions"
            :key="index"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>-->
      <el-form-item label="产品状态" prop="productStatus">
        <el-select v-model="queryParams.productStatus" @change="handleQuery" placeholder="请选择产品状态" clearable size="small">
          <el-option
            v-for="(item, index) in productStatusOptions"
            :key="index"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否暂存" prop="isStaging">
        <el-select v-model="queryParams.isStaging" @change="handleQuery" placeholder="请选择产品状态" clearable size="small">
          <el-option
            v-for="(item, index) in isStagingOptions"
            :key="index"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          size="small"
          style="width: 120px;"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['amz:productTempBasic:add']" >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['amz:productTempBasic:edit']" >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['amz:productTempBasic:remove']" >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-wallet" size="mini" :disabled="multiple" @click="handleIsStaging" v-hasPermi="['amz:productTempBasic:isStaging']" >暂存</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleClearTranslate" v-hasPermi="['amz:productTempDesc:clearTranslate']" title="清空项不包含中文和英文">清空翻译</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-sort" size="mini" :disabled="multiple" @click="handleInfringingWordReplace" v-hasPermi="['amz:productTempDesc:infringingWordReplace']" >侵权词替换</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-finished" size="mini" :disabled="multiple" @click="handleTranslate" v-hasPermi="['amz:productTempDesc:translate']" >翻译</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-upload" size="mini" @click="handleImport" v-hasPermi="['amz:productTempBasic:import']" >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-upload2" size="mini" :disabled="multiple" @click="handleExport" v-hasPermi="['amz:productTempBasic:export']" >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-s-custom" size="mini" :disabled="multiple" @click="handleClaim" v-hasPermi="['amz:productTempBasic:claim']" >认领</el-button>
      </el-col>


      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ProductTempBasicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="100"/>
      <el-table-column label="主图" align="center" prop="mainImageUrl" width="60" >
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img :src="scope.row.mainImageUrl" style="width:400px;height:400px;"/>
            <img slot="reference" :src="scope.row.mainImageUrl"  style="max-width: 40px;max-height: 40px">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="产品代码" align="center" prop="productCode" width="200" show-overflow-tooltip />
      <el-table-column label="产品分类" align="center" prop="productCategory" :formatter="productCategoryFormat" show-overflow-tooltip />
      <el-table-column label="产品来源" align="center" prop="productSourceType" :formatter="productSourceTypeFormat" show-overflow-tooltip />
      <el-table-column label="产品状态" align="center" prop="productStatus" :formatter="productStatusOptionsFormat" show-overflow-tooltip />
      <el-table-column label="认领详情" align="center" prop="claimNum">
        <template slot-scope="scope">
          <div class="cell" style="color: blue;cursor: pointer;" @click="claimNumDetail(scope.row.productCode)">{{ scope.row.claimNum }}</div>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" show-overflow-tooltip />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['amz:productTempBasic:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['amz:productTempBasic:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品基础信息对话框 -->
    <el-dialog :title="title" :visible.sync="productTempMainDialog" width="97%" :close-on-click-modal="false" style="margin-top: -15px" @close="cancel" append-to-body >
      <template>
        <el-tabs type="border-card" style="cursor: pointer;margin-top: -40px;" stretch>
          <el-tab-pane label="基本信息">
            <product_temp_add_basic ref="sonPageProductTempBasic" @setProductCode="setProductCode" @parentCloseProductTempDialog="cancel" style="height: 720px;margin-top: -20px;"></product_temp_add_basic>
          </el-tab-pane>
          <el-tab-pane label="产品关系">
            <product_temp_add_rlat ref="sonPageProductTempRlat" @setProductCode="setProductCode" @parentCloseProductTempDialog="cancel" style="height: 720px;margin-top: -20px;overflow-y: auto;"></product_temp_add_rlat>
          </el-tab-pane>
          <el-tab-pane label="产品描述">
            <product_temp_add_desc ref="sonPageProductTempDesc" @setProductCode="setProductCode" @parentCloseProductTempDialog="cancel" style="height: 720px;margin-top: -20px;"></product_temp_add_desc>
          </el-tab-pane>
        </el-tabs>

      </template>
    </el-dialog>

    <!--选择产品描述翻译内容-->
    <el-dialog title="翻译" :visible.sync="translateTypeDialog" width="55%" append-to-body :before-close="translateTypeDialogClose" >
      <translatePage v-if="translateTypeDialog" :productCodes="productCodes" pageTempOrFml="temp" @translateTypeDialogClose="translateTypeDialogClose" />
    </el-dialog>

    <!--导出产品-->
    <el-dialog title="导出" :visible.sync="exportDialog" width="60%" append-to-body>
      <el-form ref="ref_formExport" :model="formExport" :rules="rulesFormExport" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="导出方式：" prop="exportStyle">
              <el-select v-model="formExport.exportStyle" disabled placeholder="请选择导出方式" :style="{width: '100%'}">
                <el-option label="单独导出" value="one"></el-option>
                <el-option label="打包导出" value="batch" disabled></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择模板：" prop="productInitId">
              <el-select v-model="formExport.productInitId" placeholder="请选择模板(常用属性)" clearable size="small" :style="{width: '70%'}">
                <el-option
                  v-for="(item, index) in productInitOptions"
                  :key="item.productInitId"
                  :label="item.initName"
                  :value="item.productInitId"
                />
              </el-select>
              <el-button type="primary" size="mini" @click="qcIsDefaultChange">设置默认</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品分类：" prop="productCategory">
              <el-input v-model="queryParams.productCategory" disabled placeholder="请选择产品分类" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编码生成：" prop="generateExternalProductIdType">
              <el-col :span="11">
                <el-select v-model="formExport.externalProductIdType" disabled placeholder="请选择商品编码类型">
                  <el-option
                    v-for="dict in externalProductIdTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-col>

              <el-col :span="11">
                <el-select v-model="formExport.generateExternalProductIdType" placeholder="请选择商品编码生成方式">
                  <el-option
                    v-for="dict in generateExternalProductIdTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-col>

            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择站点：" prop="countryCodes">
              <el-checkbox :indeterminate="formExport.indeterminate" v-model="formExport.countryCodesCheckAll" @change="formExport_handleCheckAllChange" disabled>全选</el-checkbox>
              <div style="margin: 15px 0;"></div>
              <div>
                <el-checkbox-group v-model="formExport.countryCodes" :max="1" @change="formExport_handleCheckedCitiesChange">
                  <el-checkbox style="width: 100px" v-for="city in formExport.countryCodeOptions" :label="city.dictValue" :key="city.dictValue">{{city.dictLabel}}</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleExportSubmit">执 行</el-button>
      </div>
    </el-dialog>
    <!--认领-->
    <el-dialog title="认领" :visible.sync="claimDialog" width="50%" append-to-body>
      <el-form ref="ref_formClaim" :model="formClaim" :rules="rulesFormClaim" label-width="120px">
        <el-row>
          <el-form-item label="用户名称：" prop="userName">
            <el-select v-model="formClaim.userName" placeholder="请选择模板(常用属性)" @change="getShopcodeByUsername" clearable size="small" :style="{width: '100%'}">
              <el-option
                v-for="(item, index) in sysUserOptions"
                :key="item.userName"
                :label="item.nickName"
                :value="item.userName"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <!--暂时注释，后期可以做高级权限控制，注释有效期至2023-12-31-->
        <!--
        <el-row>
          <el-form-item label="店铺名称：" prop="shopCode">
            <el-select v-model="formClaim.shopCode" placeholder="请选择模板(常用属性)" clearable size="small" :style="{width: '100%'}">
              <el-option
                v-for="shop in shopCodeOptions"
                :key="shop.shopCode"
                :label="shop.shopName"
                :value="shop.shopCode"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="claimDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleClaimSubmit">执 行</el-button>
      </div>
    </el-dialog>
    <!--认领详情-->
    <el-dialog title="认领详情" :visible.sync="claimNumDetailDialog" width="70%" append-to-body>
      <el-table v-loading="loading" :data="claimNumDetailList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" align="center" type="index" width="50"/>
        <el-table-column label="产品代码" align="center" prop="parentProductCode" />
        <el-table-column label="新产品代码" align="center" prop="productCode"/>
        <el-table-column label="产品状态" align="center" prop="productStatus" :formatter="claimNumDetailFmlProductStatusOptionsFormat" />
        <el-table-column label="认领人" align="center" prop="createBy"/>
        <el-table-column label="认领时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!--校验结果-->
    <el-dialog title="校验结果" :visible.sync="checkDialog" width="70%" append-to-body>
      <el-table v-loading="loading" :data="productCheckList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" align="center" type="index" width="50"/>
        <el-table-column label="产品代码" align="center" prop="productCode" />
        <el-table-column label="校验类型" align="center" prop="checkType" :formatter="checkTypeFormat" width="120"/>
        <el-table-column label="校验项" align="center" prop="checkTypeItem" :formatter="checkTypeItemFormat" />
        <el-table-column label="校验状态" align="center" prop="checkStatus" :formatter="checkStatusFormat" width="120"/>
        <el-table-column label="校验说明" align="center" prop="checkDesc" />
        <el-table-column label="创建人" align="center" prop="createBy" width="120"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
      </el-table>
    </el-dialog>
    <!-- 产品导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

  import product_temp_add_basic from "./product_temp_basic";
  import product_temp_add_rlat from "./product_temp_rlat";
  import product_temp_add_desc from "./product_temp_desc";
  import translatePage from "../common/translate/translate";
  import { getToken } from "@/utils/auth";//导入
  import { importTemplate } from "@/api/amz/productTempImport";  // 导入模板接口importTemplate

  import {
    listProductTempBasic,
    delProductTempBasic,
    isStagingProductTempBasic,//暂存
    exportProductTemp,//导出产品
    productInitByCreateBy,//导出时，通过当前用户获取常用属性
    qcIsDefaultChange,
    getUserByLoginuser,//通过当前登录人获取当前用户及部门相关的用户，admin可以获取所有的正常用户信息
    claimProductTempToFml,//执行认领产品
    handleCheckProductComplete,//校验产品是否完整
    claimNumDetail,//认领详情
  } from "@/api/amz/productTempBasic";

  import {
    handleInfringingWordReplace,
    handleClearTranslate
  } from "@/api/amz/productTempDesc";

  import { getShopByUsername } from "@/api/amz/shop";
  import { getConfigCategoryByDept } from "@/api/amz/configCategory";

  export default {
    name: "productTempMain",
    components: {
      product_temp_add_basic
      ,product_temp_add_rlat
      ,product_temp_add_desc
      ,translatePage
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        productCodes: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 产品基础信息表格数据
        ProductTempBasicList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        productTempMainDialog: false,
        // 选择翻译项弹出层
        translateTypeDialog: false,
        // 导出弹框
        exportDialog: false,
        // 认领弹框
        claimDialog: false,
        // 认领详情弹框
        claimNumDetailDialog: false,
        // 认领详情数据
        claimNumDetailList: [],
        // 校验结果弹框
        checkDialog: false,
        // 校验类型：1认领校验、2上传校验字典
        checkTypeOptions: [],
        // 校验项：1变体信息、2产品主图、3产品附图、4产品描述
        checkTypeItemOptions: [],
        // 校验状态：0成功、1失败字典
        checkStatusOptions: [],
        // 产品校验数据
        productCheckList: [],
        // 上传产品弹框
        uploadToAmazonDialog: false,
        // 产品类别列表-部门
        configCategoryOptions: [],
        // 产品编码类型字典
        externalProductIdTypeOptions: [],
        // 商品编码生成方式
        generateExternalProductIdTypeOptions: [],
        // 更新删除字典
        updateDeleteOptions: [],
        // 条件类型/状况字典
        conditionTypeOptions: [],
        // 原产国/地区字典
        countryOfOriginOptions: [],
        // 产品来源字典
        productSourceTypeOptions: [],
        // 产品共享字典
        productSharingTypeOptions: [],
        // 是否佣金字典
        isCommissionTypeOptions: [],
        //产品状态
        productStatusOptions: [],
        //产品状态-认领后fml表的产品状态：1未上传；0已上传
        fmlProductStatusTypeOptions: [],
        //是否暂存
        isStagingOptions: [],
        //模板列表（常用属性）
        productInitOptions: [],
        //用户编号列表（上传产品时选择用户）
        sysUserOptions: [],
        //店铺代码列表（上传产品时选择店铺）
        shopCodeOptions: [],

        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          productCode: null,
          productCategory: null,
          productSourceType: null,
          productSharingType: null,
          isStaging: 'false',//暂存，默认不暂存false
          createBy: null,
        },
        productCode:null,//当前产品productCode
        //导出表单
        formExport:{
          exportStyle:"one",//导出方式
          productInitId: null,//常用属性值
          externalProductIdType:"EAN",//商品编码类型:UPC、EAN（默认）、ASIN 、GTIN 、ISBN 、GCID 、ISBN
          generateExternalProductIdType:"0",//商品编码生成方式：1重新生成；0补齐生成（默认）
          type:[],
          indeterminate: false,
          countryCodesCheckAll: false,
          countryCodes: [],
          countryCodeOptions:[],
          cities: [],
        },

        //认领表单
        formClaim:{
          userName:"",//用户名称，当前用户只能给自己及自己部门以下的用户认领
          shopCode: "",//可认领用户所绑定的店铺代码
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/amz/productTempBasic/importData"
        },
        //导出表单校验
        rulesFormExport: {
          exportStyle: [
            {required: true, message: "导出方式不能为空", trigger: "blur"}
          ],
          productInitId: [
            {required: true, message: "模板不能为空", trigger: "blur"}
          ],
          generateExternalProductIdType: [
            {required: true, message: "商品编码生成不能为空", trigger: "blur"}
          ],
          countryCodes: [
            {required: true, message: "站点不能为空", trigger: "blur"}
          ],
        },
        //认领表单校验
        rulesFormClaim: {
          userName: [
            {required: true, message: "用户名称不能为空", trigger: "blur"}
          ]
        },

      };
    },
    created() {
      //获取数据列表
      this.getList();
      /* 获取类目配置-部门*/
      this.getConfigCategoryByDept();
      //初始化多级字典
      this.initDicts();
    },
    methods: {
      /** 查询产品基础信息列表 */
      getList() {
        this.loading = true;
        listProductTempBasic(this.queryParams).then(response => {
          this.ProductTempBasicList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /* 获取类目配置-部门*/
      getConfigCategoryByDept(){
        getConfigCategoryByDept().then(response => {
          this.configCategoryOptions = response.data;
        });
      },

      //初始化多级字典
      initDicts(){
        this.getDicts("amz_external_product_id_type").then(response => {
          this.externalProductIdTypeOptions = response.data;
        });
        this.getDicts("qc_generate_externalProductIdType").then(response => {
          this.generateExternalProductIdTypeOptions = response.data;
        });
        this.getDicts("amz_update_delete").then(response => {
          this.updateDeleteOptions = response.data;
        });
        this.getDicts("amz_condition_type").then(response => {
          this.conditionTypeOptions = response.data;
        });
        this.getDicts("amz_country_of_origin").then(response => {
          this.countryOfOriginOptions = response.data;
        });
        this.getDicts("qc_product_source_type").then(response => {
          this.productSourceTypeOptions = response.data;
        });
        this.getDicts("qc_sharing_type").then(response => {
          this.productSharingTypeOptions = response.data;
        });
        this.getDicts("qc_is_commission_type").then(response => {
          this.isCommissionTypeOptions = response.data;
        });
        this.getDicts("qc_temp_product_status").then(response => {
          this.productStatusOptions = response.data;
        });
        this.getDicts("qc_is_boolean").then(response => {
          this.isStagingOptions = response.data;
        });
        this.getDicts("qc_country_code").then(response => {
          this.formExport.countryCodeOptions = response.data;//导出选择站点
          response.data.forEach(countryCodesObj =>{
            this.formExport.cities.push(countryCodesObj.dictValue);
          })
        });
      },
      checkDicts(){
        this.getDicts("qc_check_type").then(response => {
          this.checkTypeOptions = response.data;
        });
        this.getDicts("qc_temp_check_type_item").then(response => {
          this.checkTypeItemOptions = response.data;
        });
        this.getDicts("sys_common_status").then(response => {
          this.checkStatusOptions = response.data;
        });
      },
      // 校验类型：1认领校验、2上传校验字典翻译
      checkTypeFormat(row, column) {
        return this.selectDictLabel(this.checkTypeOptions, row.checkType);
      },
      // 校验项：1变体信息、2产品主图、3产品附图、4产品描述
      checkTypeItemFormat(row, column) {
        return this.selectDictLabels(this.checkTypeItemOptions, row.checkTypeItem);
      },
      // 校验状态：0成功、1失败字典翻译
      checkStatusFormat(row, column) {
        return this.selectDictLabel(this.checkStatusOptions, row.checkStatus);
      },
      //重置
      rest(){
        this.productCode = null;
      },
      //该方法由子页面ProductTempBasic调用，新增保存时调用
      setProductCode(formBasic){
        this.productCode = formBasic.productCode;
        //新增保存产品时，获取产品描述中的分类节点列表
        this.$refs.sonPageProductTempDesc.getRecommendedBrowseNodeOptions(this.productCode);
      },
      // 产品编码类型字典翻译
      externalProductIdTypeFormat(row, column) {
        return this.selectDictLabel(this.externalProductIdTypeOptions, row.externalProductIdType);
      },
      // 更新删除字典翻译
      updateDeleteFormat(row, column) {
        return this.selectDictLabel(this.updateDeleteOptions, row.updateDelete);
      },
      // 条件类型/状况字典翻译
      conditionTypeFormat(row, column) {
        return this.selectDictLabel(this.conditionTypeOptions, row.conditionType);
      },
      // 原产国/地区字典翻译
      countryOfOriginFormat(row, column) {
        return this.selectDictLabel(this.countryOfOriginOptions, row.countryOfOrigin);
      },
      // 产品来源字典翻译
      productSourceTypeFormat(row, column) {
        return this.selectDictLabel(this.productSourceTypeOptions, row.productSourceType);
      },
      // 产品分类字典翻译
      productCategoryFormat(row, column) {
        var categoryName = "";
        this.configCategoryOptions.forEach(obj =>{
          if (obj.categoryCode===row.productCategory){
            categoryName = obj.categoryName;
          }
        });
        if (categoryName===""){
          categoryName = row.productCategory
        }
        return categoryName;
      },
      // 产品来源字典翻译
      productStatusOptionsFormat(row, column) {
        return this.selectDictLabel(this.productStatusOptions, row.productStatus);
      },
      // 产品共享字典翻译
      productSharingTypeFormat(row, column) {
        return this.selectDictLabel(this.productSharingTypeOptions, row.productSharingType);
      },
      // 是否佣金字典翻译
      isCommissionTypeFormat(row, column) {
        return this.selectDictLabel(this.isCommissionTypeOptions, row.isCommissionType);
      },
      // 关闭Dialog弹框/取消按钮
      cancel() {
        this.productTempMainDialog = false;
        this.rest();
        //重置子页面参数-基本信息
        this.$refs.sonPageProductTempBasic.reset();
        this.$refs.sonPageProductTempRlat.reset();
        this.$refs.sonPageProductTempDesc.reset();
        this.getList();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.productCodes = selection.map(item => item.productCode)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.productCode = null;
        this.productTempMainDialog = true;
        this.title = "添加产品";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        //this.loading = true;
        this.productCode = row.productCode;
        this.productTempMainDialog = true;
        this.title = "修改产品【"+this.productCode+"】";

        /**
         * this.$nextTick 将回调延迟到下次DOM更新循环之后执行，否则无法调用到子组件属性
         */
        this.$nextTick(() => {
          //通过产品代码获取初始化数据
          this.$refs.sonPageProductTempBasic.getListByProductCode(this.productCode);
          this.$refs.sonPageProductTempRlat.getListByProductCode(this.productCode);
          this.$refs.sonPageProductTempDesc.getListByProductCode(this.productCode);
        })

      },
      /**
       * 删除按钮操作
       */
      handleDelete(row) {
        const productCodes = row.productCode || this.productCodes;
        this.$confirm('是否确认删除产品基础信息编号为"' + productCodes + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delProductTempBasic(productCodes);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /**
       * 暂存
       */
      handleIsStaging(row){
        const productCodes = row.productCode || this.productCodes;
        const reqData = new FormData();
        reqData.append("productCodes", productCodes);
        this.$confirm('是否确认暂存产品基础信息编号为"' + productCodes + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return isStagingProductTempBasic(reqData);
        }).then(response => {
          this.msgSuccess(response.msg);
          this.getList();
        })
      },

      /**
       * 侵权词替换按钮操作
       */
      handleInfringingWordReplace() {
        var self = this;
        const productCodes = self.productCodes;
        self.$confirm('是否确认替换侵权词?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          self.loading = true;
          return handleInfringingWordReplace(productCodes);
        }).then(response => {
          self.loading = false;
          self.msgSuccess(response.msg);
        }).catch((res) => {
          self.loading = false;
        });
      },
      /**
       * 清空翻译（清空项不包含中文和英文）
       */
      handleClearTranslate() {
        const productCodes = this.productCodes;
        this.$confirm('是否确认清空翻译（清空项不包含中文和英文）?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return handleClearTranslate(productCodes);
        }).then(response => {
          this.msgSuccess(response.msg);
        })
      },
      /**
       * 翻译-翻译按钮操作
       */
      handleTranslate() {
        const productCodes = this.productCodes;
        if (productCodes.length > 0) {
          this.translateTypeDialog = true;
        } else {
          this.msgError("请先选择产品数据！");
        }
      },
      // 翻译-关闭窗口
      translateTypeDialogClose() {
        this.translateTypeDialog = false
      },

      /**
       * 导出-按钮操作
       */
      handleExport: function () {

        const productCategory = this.queryParams.productCategory;
        if (!productCategory) {
          return this.msgError("请先选择搜索项【产品分类】，再进行选中导出！");
        }

        const productCodes = this.productCodes;
        if (productCodes.length > 0) {
          this.exportDialog = true;
        } else {
          this.msgError("请先选择产品数据！");
        }

        this.formExport.externalProductIdTypeOptions = this.externalProductIdTypeOptions;
        this.formExport.generateExternalProductIdTypeOptions = this.generateExternalProductIdTypeOptions;

        //通过当前用户获取常用属性（常用属性）-
        productInitByCreateBy().then(response => {
          if (response.code===200){
            this.productInitOptions = response.data;
            this.formExport.productInitId = parseInt(response.msg);//设置默认值-常用属性id
          }
        })
      },
      /**
       * 选择模板（设置常用属性）-调用productInit组件方法
       */
      qcIsDefaultChange() {
        this.msgInfo("暂时未开发，如需要设置默认，请在个人中心-常用属性中设置默认！");

        //以下代码勿删除-后续开发
      /*
       const self = this;
        self.$confirm('确认要将当前常用属性设置为默认吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          const reqDataExport = new FormData();
          reqDataExport.append("productInitId", self.formExport.productInitId);//当前self.formExport.productInitId获取的值是label，不对，后续改，先整行注释
          reqDataExport.append("qcIsDefault", "true");
          return qcIsDefaultChange(reqDataExport);
        }).then(() => {
          self.msgSuccess(text + "成功");
        });
        */
      },
      /**
       * 导出-全选站点
       */
      formExport_handleCheckAllChange(val) {
        this.formExport.countryCodes = val ? this.formExport.cities : [];
        this.formExport.indeterminate = false;
      },
      /**
       * 导出-国家代码复选框改变事件
       */
      formExport_handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.formExport.countryCodesCheckAll = checkedCount === this.formExport.cities.length;
        this.formExport.indeterminate = checkedCount > 0 && checkedCount < this.formExport.cities.length;
      },
      //导出-执行提交
      handleExportSubmit(){
        this.$refs["ref_formExport"].validate(valid => {
          if (valid) {
            var self = this;
            self.$confirm('是否确认导出产品项?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function () {
              //获取选中模板id
              let productInitChecked = self.productInitOptions.find((item) => {
                return item.productInitId === self.formExport.productInitId;
              });
              self.formExport.productInitId = productInitChecked.productInitId;

              const reqDataExport = new FormData();
              reqDataExport.append("productCategory", self.queryParams.productCategory);
              reqDataExport.append("productCodes", self.productCodes);
              reqDataExport.append("countryCodes", self.formExport.countryCodes);
              reqDataExport.append("productInitId", self.formExport.productInitId);
              reqDataExport.append("externalProductIdType", self.formExport.externalProductIdType);
              reqDataExport.append("generateExternalProductIdType", self.formExport.generateExternalProductIdType);

              return exportProductTemp(reqDataExport);

            }).then(response => {
              self.download(response.msg);
            })
          }
        })
      },

      /**
       * 认领
       */
      handleClaim(){
        const reqData = new FormData();
        reqData.append("productCodes", this.productCodes);
        this.loading = true;
        handleCheckProductComplete(reqData).then(response => {
          if (response.msg==="-1"){
            //校验未通过
            this.checkDicts();
            this.getList();
            this.checkDialog = true;
            this.productCheckList = response.data;
          }else{
            //校验通过
            this.claimDialog = true;
            //通过当前登录人获取当前用户及部门相关的用户，admin可以获取所有的正常用户信息
            getUserByLoginuser().then(response => {
              this.sysUserOptions = response.data;
            });
          }
          this.loading = false;
        }).catch((res) => {
          this.loading = false;
        });
      },
      /**
       * 认领
       * 通过用户名称获取绑定的店铺名称
       */
      getShopcodeByUsername(){
        this.shopCodeOptions = [];//清空店铺名称列表
        this.formClaim.shopCode = "";//清空店铺名称表单内容
        if (this.formClaim.userName===""){
          return;
        }
        getShopByUsername(this.formClaim.userName).then(response => {
          this.shopCodeOptions = response.data;
        });//参数为空时异常，无需处理，直接抛异常
      },
      //执行认领提交
      handleClaimSubmit(){
        this.$refs["ref_formClaim"].validate(valid => {
          if (valid) {
            var self = this;
            self.$confirm('是否确认认领产品项?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function () {
              const reqDataClaim = new FormData();
              reqDataClaim.append("productCodes", self.productCodes);
              reqDataClaim.append("userName", self.formClaim.userName);
              reqDataClaim.append("shopCode", self.formClaim.shopCode);
              return claimProductTempToFml(reqDataClaim);
            }).then(response => {
              this.claimDialog = false;
              this.getList();
              this.msgSuccess(response.msg);
            })
          }
        })
      },
      // 认领详情
      claimNumDetail(productCode){

        //获取fml表产品状态多级字典
        this.getDicts("qc_fml_product_status").then(response => {
          this.fmlProductStatusTypeOptions = response.data;
        });

        const req = new FormData();
        req.append("productCode", productCode);
        claimNumDetail(req).then(response => {
          this.claimNumDetailDialog = true;
          if (response.code===200){
            this.claimNumDetailList = response.data;
          }
        })
      },

      // 认领详情-产品状态字典
      claimNumDetailFmlProductStatusOptionsFormat(row, column) {
        return this.selectDictLabel(this.fmlProductStatusTypeOptions, row.productStatus);
      },

      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "产品导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        importTemplate().then(response => {
          this.download(response.msg);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }


    }
  };
</script>
